package simulation;

public class ValidTicTacToeState794 {
    public boolean validTicTacToe(String[] board) {
        int count_x = 0;
        int count_o = 0;
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length(); j++) {
                if (board[i].charAt(j) == 'X') {
                    count_x++;
                }
                if (board[i].charAt(j) == 'O') {
                    count_o++;
                }
            }
        }


        //后手的比先手多，或者两者相差两手之上
        if (count_o > count_x || Math.abs(count_o - count_x) > 1) {
            return false;
        }

        //两个选手都赢了
        boolean win_x = false;
        boolean win_o = false;

        //横着
        for (int i = 0; i < board.length; i++) {
            if (board[i].equals("XXX")) {
                win_x = true;
            }
            if (board[i].equals("OOO")) {
                win_o = true;
            }
        }

        //竖着
        for (int i = 0; i < board[0].length(); i++) {
            int countX = 0;
            int countO = 0;
            for (int j = 0; j < board.length; j++) {
                if (board[j].charAt(i) == 'X') {
                    countX++;
                }
                if (board[j].charAt(i) == 'O') {
                    countO++;
                }
            }
            if (countX == 3) {
                win_x = true;
            }
            if (countO == 3) {
                win_o = true;
            }
        }

        //左斜
        int countX = 0;
        int countO = 0;
        for (int i = 0; i < board.length; i++) {

            if (board[i].charAt(i) == 'X') {
                countX++;
            }
            if (board[i].charAt(i) == 'O') {
                countO++;
            }
        }
        if (countX == 3) {
            win_x = true;
        }
        if (countO == 3) {
            win_o = true;
        }
        //右斜
         countX = 0;
         countO = 0;
        for (int i = 0; i < board.length; i++) {

            if (board[i].charAt(board.length - i - 1) == 'X') {
                countX++;
            }
            if (board[i].charAt(board.length - i - 1) == 'O') {
                countO++;
            }
        }
        if (countX == 3) {
            win_x = true;
        }
        if (countO == 3) {
            win_o = true;
        }

        if (win_o && win_x) {
            return false;
        }
        if (win_x && count_x <= count_o) {
            return false;
        }

        if (win_o && count_x > count_o) {
            return false;
        }

        return true;
    }
}
